const axios = require('axios');
const { redisClient } = require('./redisConfig');
const { PassThrough } = require('stream');

// 配置参数
const CHUNK_SIZE = 200 * 1024 * 1024;       // 每个分片大小（200MB）

async function downloadAndUpload(SERVER_URL) {
    const lockKey = `lock:${SERVER_URL}`;
    const lockValue = Date.now().toString();
    let renewInterval=null;
    try {
        // 获取锁
        const isLocked = await redisClient.set(lockKey, lockValue, {
            NX: true,
            EX: 10 // 锁定 10s  1800s/30min
        });

        if (!isLocked) {
            console.log('文件正在处理');
            return;
        }

        // 定期续约锁
         renewInterval = setInterval(async () => {
            await renewLock(lockKey, lockValue);
        }, 3000); // 每 5 分钟续约一次

        // 获取文件总大小
        const fileSize = await getFileSize(SERVER_URL);
        console.log(`文件总大小: ${fileSize} bytes`);
        // 计算分片范围
        const chunks = calculateChunks(fileSize);
        console.log(`分片数量: ${chunks.length}`);
        // 下载和上传每个分片
        for (let i = 0; i < chunks.length; i++) {

            const { start, end } = chunks[i];
            await downloadChunkAndUpload(SERVER_URL, start, end, i);
        }
        // 阻塞30秒
        await new Promise(resolve => setTimeout(resolve, 30000));
        console.log('所有分片下载并上传完成');
    } catch (error) {
        console.error('处理下载时出错:', error);
    } finally {
        // 清除续约定时器
        clearInterval(renewInterval);
        // 释放锁
        await redisClient.del(lockKey);
        console.log('锁已释放');
    }
}

async function renewLock(lockKey, lockValue) {
    const script = `
    local ttl = redis.call("PTTL", KEYS[1])
        if ttl < 0 then
            return 0
        end
        if ttl <= 5000 then 
            return redis.call("PEXPIRE", KEYS[1], 10000) 
        else
            return 2
        end
    `;

    try {
        const result = await redisClient.eval(script, {
            keys: [lockKey],
        });
        if (result === 0) {
            console.log('锁已失效，无法续约');
        } else if (result === 2){
            console.log('未到时间阈值，无需续约');

        }else {
            console.log('锁已续约');
        }
    } catch (error) {
        console.error('锁续约失败:', error);
    }
}

// 获取文件总大小

async function getFileSize(SERVER_URL) {
    const headResponse = await axios.head(SERVER_URL);
    const contentLength = headResponse.headers['content-length'];
    if (!contentLength) throw new Error('无法获取文件大小');
    return parseInt(contentLength, 10);
}

// 计算分片范围

function calculateChunks(totalSize) {
    const chunks = [];
    let start = 0;
    while (start < totalSize) {
        const end = Math.min(start + CHUNK_SIZE - 1, totalSize - 1);
        chunks.push({ start, end });
        start = end + 1;
    }
    return chunks;
}

// 下载单个分片并上传到 S3

async function downloadChunkAndUpload(SERVER_URL, start, end, index) {
    const response = await axios({
        method: 'get',
        url: SERVER_URL,
        responseType: 'stream',
        headers: { Range: `bytes=${start}-${end}` }
    });

    const passThrough = new PassThrough();
    response.data.pipe(passThrough);

    console.log(`上传成功`);
}

// downloadAndUpload();

// 导出下载和上传函数

module.exports = { downloadAndUpload };